package com.gitee.wsl.platform.thread.task

import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.locks.ReentrantLock

class SysProp(key: String,  value: String?) : AutoCloseable {
    private val key: String

    private val oldValue: String?

    private val lock: ReentrantLock = locks.computeIfAbsent(key) { k: String? -> ReentrantLock() }

    init {
        lock.lock()

        this.key = key
        this.oldValue = System.getProperty(key)
        if (value == null) {
            System.clearProperty(key)
        } else {
            System.setProperty(key, value)
        }
    }

    override fun close() {
        if (oldValue == null) {
            System.clearProperty(key)
        } else {
            System.setProperty(key, oldValue)
        }
        lock.unlock()
    }

    companion object {
        private val locks: ConcurrentMap<String, ReentrantLock> = ConcurrentHashMap()

        fun with(key: String, value: String?): SysProp {
            return SysProp(key, value)
        }

        fun withVirtualThreads(enabled: Boolean): SysProp {
            return with("funfix.tasks.virtual-threads", if (enabled) "true" else "false")
        }
    }
}
